package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

//员工
@Slf4j
@RestController
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private HttpSession session;

    //当前项目的POST和PUT请求都是请求体传参的 @RequestBody
    //@RequestBody 只能标注在对象或者map之前
    @PostMapping("/employee/login")
    public ResultInfo login(@RequestBody Map<String,String> map){
        //public ResultInfo login(@RequestBody Employee employee){
        //String username = employee.getUsername();
        //String password = employee.getPassword();

        //1 接收请求参数
        String username = map.get("username");
        String password = map.get("password");
        //2 调用service进行登录
        ResultInfo resultInfo = employeeService.login(username,password);

        //3 一旦登录成功了 将employee保存到session中
        Employee employee = (Employee) resultInfo.getData();
        session.setAttribute("SESSION_EMPLOYEE",employee);
        //4 返回
        return resultInfo;
    }

    //退出
    @PostMapping("/employee/logout")
    public ResultInfo logout(){
        //1 注销当前用户的session
        session.invalidate();//  这个invalidate只会注销当前用户的session 不会动其他的session

        //2 返回成功标识
        return ResultInfo.success(null);


    }

    //员工查询
    @GetMapping("/employee/find")
    public ResultInfo findByName(String name){

        //1 调用service查询
        List<Employee> employeeList =   employeeService.findByName(name);
        //2 返回结果
        return ResultInfo.success(employeeList);

    }

    //添加员工
    @PostMapping("/employee")
    public ResultInfo save(@RequestBody Employee employee){
        log.info("接收到的参数是：" +employee);
        employeeService.save(employee);
        return  ResultInfo.success(null);
    }

    //根据id查询员工信息
    @GetMapping("/employee/{id}")
    public ResultInfo findById(@PathVariable("id") Long id){
        log.info("前端传过来的id是"+id);
        Employee employee = employeeService.finById(id);
        return ResultInfo.success(employee);
    }

    //更新
    @PutMapping("/employee")
    public ResultInfo update(@RequestBody Employee employee){
        employeeService.update(employee);
        return ResultInfo.success(null);
    }




}
